(ns
  com.marzhillstudios.molehill.import-wordpress
  (:gen-class)
  (:require
     [clojure.zip :as zip]
     [clojure.xml :as xml]
     [com.marzhillstudios.molehill.file :as mf]
     [com.marzhillstudios.list.util :as lu])
  (:use [clojure.contrib.zip-filter.xml]
     [clojure.contrib.logging]))

;; RSS file parsing functions
(defn mk-rss-tree [file]
  "mk an import file lazy seq"
  (info (str "parsing: " file))
  (zip/xml-zip (xml/parse file)))

(defn get-channel-title [tree]
  (xml-> tree :channel :title text))

(defn get-channel-entries [tree]
  (xml-> tree :channel :item ))

(defn get-entry-title [entry]
  (first (xml-> entry :title text )))

(defn get-entry-post-date [entry]
  (mf/mk-date-struct (first (xml-> entry :wp:post_date text )) "yyyy-MM-dd HH:mm:ss"))

(defn get-entry-categories [entry]
  (vec (distinct (xml-> entry :category text ))))

(defn get-entry-content [entry]
  (first (xml-> entry :content:encoded text )))

;; File creation portion
(defn entry->file [entry]
  (info (str "making hill-file from: " (get-entry-title entry)))
  (mf/new-hill-file
    (get-entry-title entry)
    (get-entry-content entry)
    (get-entry-post-date entry)
    (get-entry-categories entry)
    nil))

(defn entries->files
  "Returns a lazy sequence of hill files from a sequence of entries"
  [entries]
  (cond
    (empty? entries) ()
    :else (let [current (first entries)
                file (entry->file current)
                rst (rest entries)]
            (lu/lazy-cons* file (entries->files rst)))))

(defn process-rss [file]
  (entries->files (get-channel-entries (mk-rss-tree file))))

